<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="章节" prop="chapterId">
        <el-cascader
          :options="cascaders"
          @change="fonce()"
          :props="{ checkStrictly: true }"
          ref="casdaer"
          clearable
        ></el-cascader>
      </el-form-item>
      <el-form-item label="标题" prop="tkTitle">
        <el-input
          v-model="queryParams.tkTitle"
          placeholder="请输入标题"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="题型" prop="tkTypeId">
        <el-select
          clearable
          v-model="queryParams.tkTypeId"
          placeholder="请选择题型"
        >
          <el-option
            v-for="item in tkTypes"
            :key="item.tkTypeId"
            :label="item.tkTypeName"
            :value="item.tkTypeId"
            >{{ item.tkTypeName }}</el-option
          >
        </el-select>
      </el-form-item>
      <el-form-item label="难度" prop="difficulty">
        <el-input
          v-model="queryParams.difficulty"
          placeholder="请输入难度"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="分值" prop="score">
        <el-input
          v-model="queryParams.score"
          placeholder="请输入分值"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['tk:tk:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['tk:tk:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['tk:tk:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['tk:tk:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="tkList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="id" align="center" prop="tkId" /> -->
      <el-table-column label="章节" align="center" prop="chapterName" />
      <el-table-column
        label="标题"
        show-overflow-tooltip="true"
        align="center"
        prop="tkTitle"
      />
      <el-table-column
        label="答案"
        show-overflow-tooltip="true"
        align="center"
        prop="tkKey"
      />
      <el-table-column label="类型" align="center" prop="typeName" />
      <el-table-column label="课程" align="center" prop="courseName" />
      <el-table-column label="题型" align="center" prop="tkTypeName" />
      <el-table-column label="难度" align="center" prop="difficulty" />
      <el-table-column label="分值" align="center" prop="score" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="show(scope.row)"
            v-hasPermi="['tk:tk:edit']"
            >查看</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['tk:tk:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['tk:tk:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改题库管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="80px"
        :disabled="disabled"
      >
        <el-form-item label="章节" prop="chapterId">
          <el-cascader
            v-model="form.chapterId"
            :options="cascaders"
            clearable
          ></el-cascader>
        </el-form-item>
        <el-form-item label="难度" prop="difficulty">
          <el-radio-group v-model="form.difficulty">
            <el-radio value="简单" label="简单"></el-radio>
            <el-radio value="普通" label="普通"></el-radio>
            <el-radio value="困难" label="困难"></el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="题型" prop="tkTypeId">
          <el-select clearable v-model="form.tkTypeId" placeholder="请选择题型">
            <el-option
              v-for="item in tkTypes"
              :key="item.tkTypeId"
              :label="item.tkTypeName"
              :value="item.tkTypeId"
              >{{ item.tkTypeName }}</el-option
            >
          </el-select>
        </el-form-item>
        <el-form-item label="题目" prop="tkTitle">
          <editor
            v-model="form.tkTitle"
            placeholder="请输入"
            :min-height="192"
          />
        </el-form-item>
        <el-form-item>
           <el-switch  v-if="form.tkTypeId == 'xuanzhe1'" v-model="value1" active-text="多选" inactive-text="单选" >
        </el-switch>
        </el-form-item>
       
        <el-form-item
          label="选项"
          v-if="form.tkTypeId == 'xuanzhe1'"
          prop="option"
        >
          <el-input
            v-for="(item, index) in options"
            :key="zd[index]"
            v-model="item.optionName"
          >
            <template slot="prepend">{{ zd[index] }}</template>
          </el-input>
        </el-form-item>
        <!-- 选择题 -->
        <el-form-item
          label="答案"
          v-if="form.tkTypeId == 'xuanzhe1'"
          prop="tkKey"
        >
          <el-checkbox-group v-model="form.tkKey" :max="value1?26:1">
            <el-checkbox
              v-for="(item, index) in options"
              :key="zd[index]"
              :label="zd[index]"
              :value="zd[index]"
              name="type"
            >
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <!-- 填空题 -->
        <el-form-item
          label="答案"
          v-if="form.tkTypeId != 'xuanzhe1'"
          prop="tkKey"
        >
          <el-input
           v-if="form.tkTypeId != '26d8d5a9-3986-49e6-805f-f40ab659cd05'"
            v-model="form.tkKey"
            type="textarea"
            placeholder="请输入内容"
          />
          <el-switch  v-if="form.tkTypeId == '26d8d5a9-3986-49e6-805f-f40ab659cd05'" v-model="form.tkKey" active-text="错" inactive-text="对"> </el-switch>
        </el-form-item>

        <el-form-item v-if="form.tkTypeId == 'xuanzhe1'">
          <el-button
            size="mini"
            type="success"
            @click="add(1)"
            icon="el-icon-plus"
            circle
          ></el-button>
          <el-button
            size="mini"
            type="danger"
            @click="add(-1)"
            icon="el-icon-minus"
            circle
          ></el-button>
        </el-form-item>
        <el-form-item label="解析" prop="tkAnalys">
          <el-input
            v-model="form.tkAnalys"
            type="textarea"
            placeholder="请输入内容"
          />
        </el-form-item>

        <el-form-item label="分值" prop="score">
          <el-input-number
            :min="1"
            :max="10"
            v-model.number="form.score"
            value="2"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listTk,
  getTk,
  delTk,
  addTk,
  updateTk,
  exportTk,
  listTkType,
  listChapter,
  cascade,
  optionList,
} from "@/api/tk/tk";

export default {
  name: "Tk",
  data() {
    return {
      value1:false,
      disabled: false,
      optionsKey: [],
      options: [
        { optionName: "" },
        { optionName: "" },
        { optionName: "" },
        { optionName: "" },
      ],
      zd: [
        "A",
        "B",
        "C",
        "D",
        "E",
        "F",
        "G",
        "H",
        "I",
        "J",
        "K",
        "L",
        "M",
        "N",
        "O",
        "P",
        "Q",
        "R",
        "S",
        "T",
        "U",
        "V",
        "W",
        "X",
        "Y",
        "Z",
      ],
      //是否有选项
      isXx: false,
      //级联数据
      cascaders: [],
      //题型
      tkTypes: [],
      //章节
      chapters: [],
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedQtChapter: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 题库管理表格数据
      tkList: [],
      // 章节管理表格数据
      qtChapterList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        chapterId: null,
        tkTitle: null,
        tkKey: null,
        tkAnalys: null,
        tkTypeId: null,
        difficulty: null,
        score: null,
        typeId: null,
        courseId: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        chapterId: [{ required: true, message: "必填项，不可为空" }],
        difficulty: [{ required: true, message: "必填项，不可为空" }],
        tkTypeId: [{ required: true, message: "必填项，不可为空" }],
        tkTitle: [{ required: true, message: "必填项，不可为空" }],
        // tkKey: [{ required: true,message:'必填项，不可为空' }],
        // option: [{ required: true,message:'必填项，不可为空' }],
        score: [{ required: true, message: "必填项，不可为空" }],
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    add(param) {
      const l = this.options.length + param;
      if (l > 1 && l <= 26) {
        if (param == 1) {
          this.options.push({});
        } else {
          this.options.pop();
        }
        this.options.length = l;
      } else if (l == 1) {
        this.$message.error("最低有两个选项");
      }
    },
    //渲染级联数据
    fonce() {
      const date = this.$refs["casdaer"].getCheckedNodes()[0];
      console.log(date);
      this.queryParams.typeId =null;
      this.queryParams.courseId = null;
      this.queryParams.chapterId = null;
      if (date.level == 1) {
        this.queryParams.typeId = date.value;
      } else if (date.level == 2) {
        this.queryParams.courseId = date.value;
      } else {
        this.queryParams.chapterId = date.value;
      }
    },
    /** 查询题库管理列表 */
    getList() {
      this.loading = true;
      listTk(this.queryParams)
        .then((response) => {
          this.tkList = response.rows;
          this.total = response.total;
          this.loading = false;
        })
        .then(() => {
          this.getChapter();
          this.gettkType();
          this.getCascade();
        });
    },
    /** 获取级联数据 */
    getCascade() {
      cascade().then((res) => {
        this.cascaders = res;
      });
    },
    /** 获取章节数据 */
    getChapter() {
      listChapter().then((res) => {
        this.chapters = res.rows;
      });
    },
    /** 获取类型数据 */
    gettkType() {
      listTkType().then((res) => {
        this.tkTypes = res.rows;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        tkId: null,
        chapterId: null,
        tkTitle: null,
        tkKey: [],
        tkAnalys: null,
        tkTypeId: null,
        difficulty: null,
        score: null,
        tkStr: null,
        tkInt: null,
        options: [
          { optionName: "" },
          { optionName: "" },
          { optionName: "" },
          { optionName: "" },
        ],
      };
      this.disabled = false;
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.tkId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.options = [
        { optionName: "" },
        { optionName: "" },
        { optionName: "" },
        { optionName: "" },
      ];
      this.open = true;
      this.title = "录题";
    },
    show(row) {
      this.handleUpdate(row);
      this.disabled = true;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const tkId = row.tkId || this.ids;
      getTk(tkId)
        .then((response) => {
          this.form = response.data;
          this.form.tkKey = this.form.tkKey.split(",");
          this.open = true;
          this.title = "修改题库管理";
        })
        .then(() => {
          optionList({ tkId: tkId }).then((res) => {
            this.options = res;
            this.options.forEach((element) => {
              element.optionName = element.optionName.substr(2);
            });
          });
        });
    },
    appendZ(options) {
      for (var i = 0; i < this.options.length; i++) {
        options[i].optionName = this.zd[i] + ":" + options[i].optionName;
      }
      return options;
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.tkTypeId == "xuanzhe1") {
            this.form.tkKey = this.form.tkKey.join(",");
          }

          this.form.options = this.appendZ(this.options);
          if (this.form.chapterId.length <= 3) {
            this.form.typeId = this.form.chapterId[0];
            this.form.courseId = this.form.chapterId[1];
            this.form.chapterId = this.form.chapterId[2];
          }
          if (this.form.tkId != null) {
            updateTk(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addTk(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const tkIds = row.tkId || this.ids;
      this.$modal
        .confirm('是否确认删除题库管理编号为"' + tkIds + '"的数据项？')
        .then(function () {
          return delTk(tkIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 章节管理序号 */
    rowQtChapterIndex({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },
    /** 章节管理添加按钮操作 */
    handleAddQtChapter() {
      let obj = {};
      obj.chapterName = "";
      obj.chapterParentId = "";
      obj.courseId = "";
      this.qtChapterList.push(obj);
    },

    /** 复选框选中数据 */
    handleQtChapterSelectionChange(selection) {
      this.checkedQtChapter = selection.map((item) => item.index);
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$modal
        .confirm("是否确认导出所有题库管理数据项？")
        .then(() => {
          this.exportLoading = true;
          return exportTk(queryParams);
        })
        .then((response) => {
          this.$download.name(response.msg);
          this.exportLoading = false;
        })
        .catch(() => {});
    },
  },
};
</script>
